package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.commom.BaseContext;
import com.itheima.reggie.commom.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录过滤器
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //路径匹配器

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestUrl = request.getRequestURI();
        String[] url = new String[] {
                "/employee/login", "/employee/logout","/user/sendMsg",
                "/backend/**", "/front/**","/user/login"
        };

        log.info("拦截请求:"+requestUrl);
        boolean check = check(url, requestUrl);
        //包含放行路径
        if (check){
            filterChain.doFilter(request,response);
            return;
        }

        //已经登录放行
        if (request.getSession().getAttribute("employee") != null){
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentID(empId);
            filterChain.doFilter(request,response);
            return;
        }

        //已经登录放行user
        if (request.getSession().getAttribute("user") != null){
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentID(userId);
            filterChain.doFilter(request,response);
            return;
        }
        //未登录返回未登录跳转登录页
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;
    }


    public boolean check(String[] urls ,String requestUrl) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestUrl);
            if (match) return true;
        }
        return false;
    }
}
